package com.m3958.firstgwt.server.filter;


import java.io.IOException;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.m3958.firstgwt.server.model.WebSite;
import com.m3958.firstgwt.server.service.AppUtilService;
import com.m3958.firstgwt.server.service.Monitor;
import com.m3958.firstgwt.server.service.RequestScopeObjectService;
import com.m3958.firstgwt.server.service.ServiceDelayStartService;

@Singleton
public class MonitorFilter implements Filter{
	
	@Inject
	private Monitor monitor;
	
	@Inject
	private Injector injector;
	
	@Inject
	private AppUtilService auservice;
	
	@Inject
	private ServiceDelayStartService sds;
	
//	@Inject
//	private ChangeLogConsumerThread cct;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
			
			if(request instanceof HttpServletRequest){
				String uri = ((HttpServletRequest)request).getRequestURI();
				if(uri.startsWith("/showtimes")){
					((HttpServletResponse)response).setStatus(HttpServletResponse.SC_NOT_FOUND);
					return;
				}
			}
			
			monitor.increaseRequestCounter();
//			HttpServletResponse res = (HttpServletResponse) response;
//			HttpServletRequest req = (HttpServletRequest) request;
//			RequestScopeObjectService rso = injector.getInstance(RequestScopeObjectService.class);
//			WebSite ws = rso.getRequestWebSite();
//			if(ws != null && ws.getUnitPrice() > 1){
//				if(ws.getServiceEndDate().getTime() < new Date().getTime()){
//					auservice.writeHtmlResponse(res, "您的网站已欠费停机！");
//					return;
//				}
//			}
			
			chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		sds.start();
//		cct.start();
	}
	
	@Override
	public void destroy() {
		sds.stop();
	}

}
